package cn.jn.lhm.netty.part07;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/10/29 - 21:29
 **/
@SuppressWarnings("all")
@Slf4j
public class ShortConnectClient {


    public static byte[] makeStr(char c, int length) {
        int max = length - 1;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < max; i++) {
            builder.append(c);
        }
        builder.append("\t");
        return builder.toString().getBytes(StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            ChannelFuture future = bootstrap.channel(NioSocketChannel.class)
                    .group(worker)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel client) throws Exception {
                            client.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            client.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                                /**
                                 * 会在channel连接建立成功会触发
                                 */
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    char a = '0';
                                    Random r = new Random();
                                    for (int i = 0; i < 10; i++) {
                                        ByteBuf buffer = ctx.alloc().buffer(16);
                                        buffer.writeBytes(makeStr(a, r.nextInt(256) + 1));
                                        ctx.writeAndFlush(buffer);
                                        a++;
                                    }
                                    client.close();
                                }
                            });
                        }
                    })
                    .connect(new InetSocketAddress("Localhost", 8080))
                    .sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("Client Error...", e);
        } finally {
            worker.shutdownGracefully();
        }

    }
}
